package com.zhong.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhong.blog.mapper.EssayMapper;
import com.zhong.blog.pojo.Essay;
import com.zhong.blog.pojo.User;
import com.zhong.blog.service.EssayService;
import com.zhong.blog.service.UserService;
import com.zhong.blog.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/essay")
public class EssayController {
    @Autowired
    UserService userService;

    @Autowired
    EssayService essayService;
    @Autowired
    EssayMapper essayMapper;

    @PostMapping("/save")
    public R saveEssay(@RequestBody Essay essay){
        System.out.println("===保存随笔===");
        System.out.println(essay.toString());

        List<User> users = userService.queryByName(essay.getUsername());
        essay.setImgurl(users.get(0).getImgurl());
        essayService.save(essay);
        return R.ok();
    }

    @GetMapping("getData")
    public R getData(@RequestParam("page") int page,@RequestParam("size") int size){

        System.out.println("===查询数据==");
        System.out.println(page+""+size);

        QueryWrapper<Essay> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        Page<Essay> essayPage = new Page<>(page,size);
        essayMapper.selectPage(essayPage, wrapper);
        List<Essay> essays = essayPage.getRecords();
        long total = essayPage.getTotal();
        return R.ok().put("essays",essays).put("total",total);
    }


}
